﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Net;
using Newtonsoft.Json.Linq;
using System.Web;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Specialized;

namespace MTA.TripPlanner
{

    public abstract class BaseFeed<T>
    {
        protected int _id = -1;

        public int Id { get { return _id; } }

        public delegate JToken GetJArrayDelegate(JObject obj);

        public delegate T ConvertOneDelegate(JObject obj);

        public static JObject LoadFromCache(String cachefile)
        {

            if (File.Exists(cachefile))
            {
                using (StreamReader sr = new StreamReader(cachefile))
                {
                    using (JsonTextReader tr = new JsonTextReader(sr))
                    {
                        try
                        {
                            return JObject.Load(tr);
                        }
                        catch
                        {
                            return null;
                        }
                    }
                }
            }
            return null;
        }

        public static List<T> ConvertJSONArray(JSONRequest request, GetJArrayDelegate getarr, ConvertOneDelegate converter, bool cacheResults)
        {
            JObject data = null;
            if (cacheResults)
                data = LoadFromCache(request.Params.GetCachePage());
            if (data == null)
            {
                data = request.MakeRequest();
                if (cacheResults == true)
                {
                    String page = request.Params.GetCachePage();
                    using (StreamWriter sr = new StreamWriter(page))
                    {
                        sr.Write(data.ToString());
                    }
                }
            }

            JToken arr = getarr(data);
            // make sure an array is there... sometimes it just returns null
            if (arr is JArray && (((JArray)arr)[0] is JObject))
                return (from JObject r in (JArray)arr
                        select converter(r)).ToList();
            else
                return null;
        }

    }


}
